<template>
    <div>
        <div class="ccui-navigation">
            <el-button
                size="mini"
                type="primary-icon-medium"
                icon="icon-ccui-return"
                @click="handleBack"
            >返回
            </el-button
            >
            <div class="ccui-navigation-divider"/>
            <!-- 面包屑 -->
            <el-breadcrumb
                class="ccui-navigation-crumbs-container"
                separator-class="el-icon-arrow-right"
            >
                <el-breadcrumb-item
                    :to="{ path: $store.getters.getBreadcrumb('level1').path }"
                >{{ $store.getters.getBreadcrumb("level1").name }}
                </el-breadcrumb-item>
                <el-breadcrumb-item :to="{ path: '/invoice/Entering/toSubmit' }"
                >发票管理
                </el-breadcrumb-item>
                <el-breadcrumb-item
                    :to="{
            path: '/invoice/manage'
          }"
                >发票冲销
                </el-breadcrumb-item>
                <el-breadcrumb-item>
                    <span class="ccui-curr-crumb">新增</span>
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        
        <div class="ccui-app-container-detail">
            <div class="ccui-app-container-detail-body">
                <el-tabs v-model="activeName" class="el-tabs__customize">
                    <el-tab-pane label="基本信息" name="first">
                        <baseInfo
                            labelWidth="130px"
                            ref="baseInfo"
                            @getTableList="getTableList"
                        />
                        <!--  -->
                    </el-tab-pane>
                     <el-tab-pane label="款项明细" name="fundDetail">
                       <fund-detail/>
                    </el-tab-pane>
                    <el-tab-pane label="发票清单" name="second">
                        <!-- <invoiceList ref="tableBill" :tableBill="tableBill"/> -->
                        <!-- <invoiceList/> -->
                        <div class="ccui-multifunctional-table-wrapper">
                            <ux-grid
                                align="center"
                                ref="multipleTable"
                                :data="tableBill"
                                :isshow="true"
                                border
                                max-height="9999"
                                class="ccui-multifunctional-table"
                                :summary-method="getSummariesBill"
                                lazy
                                show-summary
                                keep-source
                                :highlightCurrentRow="false"
                                :widthResize="true"
                                :edit-config="{ trigger: 'click', mode: 'cell' }"
                            >
                                <!-- <ux-table-column
                                  type="checkbox"
                                  fixed="left"
                                  width="55"
                                ></ux-table-column> -->
                                <ux-table-column
                                    type="index"
                                    title="序号"
                                    width="80"
                                    fixed="left"
                                />
                                <template v-for="(table, index) in tableColumnBill">
                                    <ux-table-column
                                        :key="index"
                                        :field="table.prop"
                                        :title="table.label"
                                        :width="table.width"
                                        :align="table.align"
                                        :header-align="table.headAlign"
                                        show-overflow-tooltip
                                    />
                                </template>
                            </ux-grid>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="发票信息" name="three">
                        <!-- <invoiceInfo ref="tableInfo" :tableInfo="tableInfo"/> -->
                        <!-- <invoiceInfo /> -->
                        <div class="ccui-multifunctional-table-wrapper">
                            <el-table
                                align="center"
                                ref="multipleTable"
                                :data="tableInfo"
                                :isshow="true"
                                border
                                max-height="9999"
                                class="ccui-multifunctional-table"
                                :header-cell-class-name="must"
                                :summary-method="getSummariesInfo"
                                lazy
                                show-summary
                                :cell-style="cellStyle"
                            >
                                <el-table-column
                                    type="index"
                                    label="序号"
                                    width="80"
                                    fixed="left"
                                />
                                <template v-for="(table, index) in tableColumnInfo">
                                    <el-table-column
                                        :key="index"
                                        :prop="table.prop"
                                        :label="table.label"
                                        :fixed="table.fixed"
                                        :width="table.width"
                                        :align="table.align"
                                        :header-align="table.headAlign"
                                        show-overflow-tooltip
                                    />
                                </template>
                            </el-table>
                        </div>
                    </el-tab-pane>
                    <el-tab-pane label="附件" name="four">
                        <attachment
                        :requiredCell="true"
                            ref="attachment"
                            :table-data="fileList"
                            class="commonClass"
                        ></attachment>
                    </el-tab-pane>
                </el-tabs>
            </div>
        </div>
        
        <el-bottom-guide>
            <ul class="ccui-bottom-button">
                <!-- <li>
                  <el-button type="bottom" icon="icon-ccui-save" @click="timeKeep"
                    >暂存</el-button
                  >
                </li> -->
                <li>
                    <el-button type="bottom" icon="icon-ccui-save" @click="saveMessage"
                    >保存并校验
                    </el-button
                    >
                </li>
                <li>
                    <el-button
                        type="bottom"
                        icon="icon-ccui-export"
                        @click="submitMessage"
                    >保存并提交
                    </el-button
                    >
                </li>
                <div class="ccui-bottom-guide-divider"/>
                <li>
                    <el-button type="bottom" icon="icon-ccui-return" @click="handleBack"
                    >返回
                    </el-button
                    >
                </li>
            </ul>
        </el-bottom-guide>
    </div>
</template>

<script>
import baseInfo from "../components/baseInfo";
import fundDetail from "../components/fundDetail"
// import invoiceList from "../components/invoiceList";
// import invoiceInfo from "../components/invoiceInfo";
import {formatNumber} from "@/basa/utils";
// import attachment from "../../invoiceEntering/components/attachment.vue";
import attachment from "@/basa/components/public/uploadInfo2";

import {
    saveInvoiceWriteOff,
    submitInvoiceWriteOff,
    // tempSaveInvoiceWriteOff
} from "../api";

export default {
    data() {
        return {
            activeName: "first",
            tableBill: [],
            tableColumnBill: [
                {
                    prop: "storageCode",
                    label: "入库单编号",
                    width: "180",
                    headAlign: "left"
                },
                {
                    prop: "storageName",
                    label: "入库单名称",
                    width: "300",
                    headAlign: "left"
                },
                {
                    prop: "materialsCode",
                    label: "设备物资编码",
                    width: "110",
                    headAlign: "left"
                },
                {
                    prop: "materialsName",
                    label: "设备物资名称",
                    width: "300",
                    headAlign: "left"
                },
                {
                    prop: "materialsDescribe",
                    label: "设备物资说明",
                    width: "200",
                    headAlign: "left"
                },
                {
                    prop: "currentMeasuringUnit",
                    label: "计量单位",
                    width: "120",
                    headAlign: "left"
                },
                {
                    prop: "currentNum",
                    label: "数量",
                    width: "100",
                    headAlign: "left"
                },
                {
                    prop: "unitPriceWithoutTax",
                    label: "不含税单价",
                    width: "130",
                    align: "right",
                    headAlign: "left"
                },
                {
                    prop: "price",
                    label: "含税单价",
                    width: "130",
                    align: "right",
                    headAlign: "left"
                },
                {
                    prop: "rate",
                    label: "税率",
                    width: "100",
                    formatterName: "rate",
                    align: "right",
                    headAlign: "left"
                },
                {
                    prop: "amountExcludeTax",
                    label: "不含税金额",
                    width: "130",
                    align: "right",
                    headAlign: "left"
                },
                {
                    prop: "tax",
                    label: "税额",
                    width: "130",
                    formatterName: "tax",
                    align: "right",
                    headAlign: "left"
                },
                {
                    prop: "amount",
                    label: "含税金额",
                    width: "130",
                    align: "right",
                    headAlign: "left"
                },
                {
                    prop: "remark",
                    label: "备注",
                    width: "100",
                    headAlign: "left"
                }
            ],
            tableInfo: [],
            tableColumnInfo: [
                {
                    prop: "invoiceTypeName",
                    label: "发票类型",
                    // fixed: "left",
                    width: "100",
                    headAlign: "left",
                    align: "left"
                },
                {
                    prop: "invoiceNo",
                    label: "发票号码",
                    // fixed: "left",
                    width: "130",
                    headAlign: "left",
                    align: "left"
                },
                {
                    prop: "invoiceCode",
                    label: "发票代码",
                    width: "130",
                    headAlign: "left",
                    align: "left"
                },
                // {
                //     prop: "ratePercent",
                //     label: "税率",
                //     width: "100",
                //     headAlign: 'left',
                //     align: "right"
                // },
                {
                    prop: "priceTaxTotal",
                    label: "价税合计",
                    width: "130",
                    headAlign: "left",
                    align: "right"
                },
                {
                    prop: "tax",
                    label: "税额",
                    width: "130",
                    headAlign: "left",
                    align: "right"
                },
                {
                    prop: "amountExcludeTax",
                    label: "不含税金额",
                    width: "130",
                    headAlign: "left",
                    align: "right"
                },
                {
                    prop: "invoiceDate",
                    label: "开票日期",
                    width: "150",
                    headAlign: "left",
                    align: "left"
                },
                {
                    prop: "seller",
                    label: "销售方名称",
                    width: "150",
                    headAlign: "left",
                    align: "left"
                },
                {
                    prop: "purchaser",
                    label: "购买方名称",
                    width: "150",
                    headAlign: "left",
                    align: "left"
                },
                {
                    prop: "remake",
                    label: "备注",
                    width: "100",
                    headAlign: "left",
                    align: "left"
                }
            ],
            fileList: [],
            fileData: []
        };
    },
    methods: {
        getTableList(message) {
            //   if (this.$route.query.newAdd != 1) {
            this.tableBill = message.invoceBill; //发票清单
            this.tableBill.forEach(v => {
                v.currentNum = formatNumber(v.currentNum, 3);
                v.unitPriceWithoutTax = Number(v.unitPriceWithoutTax).toFixed(2);
                v.price = Number(v.price).toFixed(2);
                v.rate = new this.$BigNumber(Number(v.rate)).multipliedBy(100) + "%";
                v.amountExcludeTax = Number(v.amountExcludeTax).toFixed(2);
                v.tax = Number(v.tax).toFixed(2);
                v.amount = Number(v.amount).toFixed(2);
            });
            this.tableInfo = message.invoceInfo; //发票信息
            console.log('this.tableInfo', this.tableInfo)
            this.tableInfo.forEach(v => {
                v.priceTaxTotal = Number(v.priceTaxTotal).toFixed(2);
                v.rate = new this.$BigNumber(Number(v.rate)).multipliedBy(100) + "%";
                v.tax = Number(v.tax).toFixed(2);
                v.amountExcludeTax = Number(v.amountExcludeTax).toFixed(2);
                if (v.invoiceDate) {
                    v.invoiceDate = (v.invoiceDate).substring(0, 10);
                }
                
            });
            this.fileList = message.files; //附件信息
            this.fileList.forEach(item => {
                item.createTime = item.uploadTime;
                //   item.fileSize =
                //     item.fileSize.substr(0, item.fileSize.length - 3) + "KB";
                item.uploadId = item.fileInfoId;
            });
            // var fileIds = [];
            // for (let i = 0; i < this.fileList.length; i++) {
            //   fileIds.push(this.fileList[i].fileInfoId);
            // }
            var fileIds = [];
            for (let i = 0; i < this.fileList.length; i++) {
                fileIds[i] = {};
                fileIds[i].fileDesc = this.fileList[i].fileDesc;
                fileIds[i].fileInfoId = this.fileList[i].fileInfoId;
                fileIds[i].uploadId = this.fileList[i].uploadId;
                fileIds[i].uploadTime = this.fileList[i].uploadTime;
                fileIds[i].createTime = this.fileList[i].uploadTime;
                fileIds[i].fileName = this.fileList[i].fileName;
                fileIds[i].fileSize = this.fileList[i].fileSize;
                
            }
            this.$refs.attachment.fileList = fileIds;
            //   }
        },
        handleBack() {
            this.$router.go(-1);
        },
        // 暂存
        // timeKeep() {
        //   let baseObj = {
        //     // id: this.$refs["baseInfo"].formData.id, //主键 新增保存不用传
        //     invoiceBasicId: this.$refs["baseInfo"].formData.invoiceBasicId, //发票基本信息id
        //     writeOffName: this.$refs["baseInfo"].formData.writeOffName, //冲销单名称
        //     writeOffReason: this.$refs["baseInfo"].formData.writeOffReason, //冲销原因
        //     writeOffAmount: this.$refs["baseInfo"].formData.writeOffAmount, //冲销金额
        //     // writeOffStatus: this.$refs["baseInfo"].formData.writeOffStatus,   //冲销审批状态
        //     // writeOffApproveStatus: this.$refs["baseInfo"].formData.writeOffApproveStatus,   //冲销审批通过时间
        //     // writeOffApproveTime: this.$refs["baseInfo"].formData.writeOffApproveTime,
        //     reportInOrgId: this.$refs["baseInfo"].formData.reportInOrgId, //填报单位id
        //     reportInOrgName: this.$refs["baseInfo"].formData.reportInOrgName, //填报单位名称
        //     reportInAuthCode: this.$refs["baseInfo"].formData.reportInAuthCode, //填报单位4A编码
        //     reportOrgDeptId: "0", //填报单位部门
        //     reportOrgDeptName: "填报部门名称", //填报单位部门名称
        //     compileUser: this.$refs["baseInfo"].formData.compileUser, //编制人姓名
        //     compileDate: Date.parse(this.$refs["baseInfo"].formData.compileDate) //编制日期
        //   };
        //   let arrNum = this.$refs.attachment.fileList.length;
        //     for(let i = 0; i < arrNum ; i++){
        //       this.fileData[i]={};
        //     this.fileData[i].uploadTime = this.$refs.attachment.fileList[i].createTime;
        //     this.fileData[i].uploadId = this.$refs.attachment.fileList[i].uploadId;
        //     this.fileData[i].fileDesc = this.$refs.attachment.fileList[i].fileDesc;
        //     this.fileData[i].sn = this.$refs.attachment.fileList[i].sn;
        //     }
        //   let obj = {
        //     invoiceWriteOffBO: baseObj,
        //     // uploadIds: this.$refs.attachment.uploadIds
        //     files:this.fileData
        //   };
        //   tempSaveInvoiceWriteOff(obj).then(res => {
        //     if (res.data.code == "0") {
        //       this.$message({
        //         type: "success",
        //         message: res.data.message,
        //         showClose: true,
        //         ccuiCustom: true,
        //         duration:3000
        //       });
        //       this.$router.push("/invoice/manage/to-submit");
        //     }
        //   });
        // },
        // 保存
        saveMessage() {
            let baseObj = {
                // id: this.$refs["baseInfo"].formData.id, //主键 新增保存不用传
                invoiceBasicId: this.$refs["baseInfo"].formData.invoiceBasicId, //发票基本信息id
                writeOffName: this.$refs["baseInfo"].formData.writeOffName, //冲销单名称
                writeOffReason: this.$refs["baseInfo"].formData.writeOffReason, //冲销原因
                writeOffAmount: this.$refs["baseInfo"].formData.writeOffAmount, //冲销金额
                // writeOffStatus: this.$refs["baseInfo"].formData.writeOffStatus,   //冲销审批状态
                // writeOffApproveStatus: this.$refs["baseInfo"].formData.writeOffApproveStatus,   //冲销审批通过时间
                // writeOffApproveTime: this.$refs["baseInfo"].formData.writeOffApproveTime,
                reportInOrgId: this.$refs["baseInfo"].formData.reportInOrgId, //填报单位id
                reportInOrgName: this.$refs["baseInfo"].formData.reportInOrgName, //填报单位名称
                reportInAuthCode: this.$refs["baseInfo"].formData.reportInAuthCode, //填报单位4A编码
                reportOrgDeptId: "0", //填报单位部门
                reportOrgDeptName: "填报部门让你", //填报单位部门名称
                compileUser: this.$refs["baseInfo"].formData.compileUser, //编制人姓名
                compileDate: Date.parse(this.$refs["baseInfo"].formData.compileDate) //编制日期
            };
            let arrNum = this.$refs.attachment.fileList.length;
            if(!arrNum){
                this.$message.error('请上传附件')
                return
            }
            for (let i = 0; i < arrNum; i++) {
                this.fileData[i] = {};
                this.fileData[i].uploadTime = this.$refs.attachment.fileList[i].createTime;
                this.fileData[i].uploadId = this.$refs.attachment.fileList[i].uploadId;
                this.fileData[i].fileDesc = this.$refs.attachment.fileList[i].fileDesc;
                this.fileData[i].sn = this.$refs.attachment.fileList[i].sn;
            }
            let obj = {
                invoiceWriteOffBO: baseObj,
                // uploadIds: this.$refs.attachment.uploadIds
                files: this.fileData
            };
            saveInvoiceWriteOff(obj).then(res => {
                if (res.data.code == "0") {
                    this.$message({
                        type: "success",
                        message: res.data.message,
                        showClose: true,
                        ccuiCustom: true,
                        duration: 3000
                    });
                    this.$router.push("/invoice/manage/to-submit");
                }
            });
        },
        // 提交
        submitMessage() {
            let baseObj = {
                invoiceBasicId: this.$refs["baseInfo"].formData.invoiceBasicId, //发票基本信息id
                writeOffName: this.$refs["baseInfo"].formData.writeOffName, //冲销单名称
                writeOffReason: this.$refs["baseInfo"].formData.writeOffReason, //冲销原因
                writeOffAmount: this.$refs["baseInfo"].formData.writeOffAmount, //冲销金额
                // writeOffStatus: this.$refs["baseInfo"].formData.writeOffStatus,   //冲销审批状态
                // writeOffApproveStatus: this.$refs["baseInfo"].formData.writeOffApproveStatus,   //冲销审批通过时间
                // writeOffApproveTime: this.$refs["baseInfo"].formData.writeOffApproveTime,
                reportInOrgId: this.$refs["baseInfo"].formData.reportInOrgId, //填报单位id
                reportInOrgName: this.$refs["baseInfo"].formData.reportInOrgName, //填报单位名称
                reportInAuthCode: this.$refs["baseInfo"].formData.reportInAuthCode, //填报单位4A编码
                reportOrgDeptId: "0", //填报单位部门
                reportOrgDeptName: "填报部门让你", //填报单位部门名称
                compileUser: this.$refs["baseInfo"].formData.compileUser, //编制人姓名
                compileDate: Date.parse(this.$refs["baseInfo"].formData.compileDate) //编制日期
            };
            let arrNum = this.$refs.attachment.fileList.length;
            if(!arrNum){
                this.$message.error('请上传附件')
                return
            }
            for (let i = 0; i < arrNum; i++) {
                this.fileData[i] = {};
                this.fileData[i].uploadTime = this.$refs.attachment.fileList[i].createTime;
                this.fileData[i].uploadId = this.$refs.attachment.fileList[i].uploadId;
                this.fileData[i].fileDesc = this.$refs.attachment.fileList[i].fileDesc;
                this.fileData[i].sn = this.$refs.attachment.fileList[i].sn;
            }
            let obj = {
                invoiceWriteOffBO: baseObj,
                // uploadIds: this.$refs.attachment.uploadIds
                files: this.fileData
            };
            submitInvoiceWriteOff(obj).then(res => {
                if (res.data.code == "0") {
                    this.$message({
                        type: "success",
                        message: res.data.message,
                        showClose: true,
                        ccuiCustom: true,
                        duration: 3000
                    });
                    this.$router.push("/invoice/manage/all-list");
                }
            });
        },
        // 发票清单
        getSummariesBill(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                if (
                    ["currentNum", "amount", "amountExcludeTax", "tax"].includes(
                        column.property
                    )
                ) {
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                let num = Number(prev) + Number(curr);
                                return num;
                            } else {
                                return Number(prev);
                            }
                        }, 0);
                        if (index == 11 || index == 12 || index == 13 || index == 14) {
                            sums[index] = Number(sums[index]).toFixed(2);
                            //   console.log(sums[index])
                        }
                        if (index == 7 || index == 8) {
                            sums[index] = Number(sums[index]).toFixed(3);
                            
                        }
                    }
                }
            });
            return [sums];
        },
        // 发票信息
        getSummariesInfo(param) {
            const {columns, data} = param;
            const sums = [];
            columns.forEach((column, index) => {
                if (index === 0) {
                    sums[index] = "合计";
                    return;
                }
                if (
                    [
                        "priceTaxTotal",
                        "deductionRate",
                        "amountExcludeTax",
                        "tax",
                        "deductionTax"
                    ].includes(column.property)
                ) {
                    const values = data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                let num = Number(prev) + Number(curr);
                                return num;
                            } else {
                                return Number(prev);
                            }
                        }, 0);
                        if (
                            index == 5 ||
                            index == 6 ||
                            index == 7 ||
                            index == 8 ||
                            index == 9
                        ) {
                            sums[index] = Number(sums[index]).toFixed(2);
                        }
                    }
                }
            });
            // 价税合计=本次收票金额（基本信息）
            sums.forEach((e, i) => {
                if (i == 5) {
                    this.$bus.$emit("priceTaxTotalSum", e);
                }
            });
            return sums;
        },
        cellStyle(data) {
            let index = data.columnIndex
            if (index == 5 ||
                index == 6 ||
                index == 7 ||
                index == 8 ||
                index == 9) {
                return "text-align:right"
            }
        },
        must(obj) {
            if (
                obj.columnIndex == 0 ||
                obj.columnIndex == 9 ||
                obj.columnIndex == 10
            ) {
                return;
            } else {
                return "must";
            }
        }
    },
    activated() {
        this.activeName = "first";
        this.fileData = [];
        this.tableBill = [];
        this.tableInfo = [];
        this.fileList = [];
    },
    components: {
        baseInfo,
        // invoiceList,
        // invoiceInfo,
        attachment,
        fundDetail
    },
    mounted() {
        this.$bus.$on("getTableList", data => {
            this.tableBill = data;
            // this.tableBill.forEach(v => {
            //   v.currentNum = formatNumber(v.currentNum, 3);
            //   v.unitPriceWithoutTax = Number(v.unitPriceWithoutTax).toFixed(2);
            //   v.price = Number(v.price).toFixed(2);
            //   v.rate = new this.$BigNumber(Number(v.rate)).multipliedBy(100) + "%";
            //   v.amountExcludeTax = Number(v.amountExcludeTax).toFixed(2);
            //   v.tax = Number(v.tax).toFixed(2);
            //   v.amount = Number(v.amount).toFixed(2);
            // });
        })
        this.$bus.$on("getTableListInfo", data => {
            this.tableInfo = data;
            this.tableInfo.forEach(v => {
                v.priceTaxTotal = Number(v.priceTaxTotal).toFixed(2);
                // v.rate = new this.$BigNumber(Number(v.rate)).multipliedBy(100) + "%";
                // v.tax = Number(v.tax).toFixed(2);
                // v.amountExcludeTax = Number(v.amountExcludeTax).toFixed(2);
                // if(v.invoiceDate){
                //     v.invoiceDate = (v.invoiceDate).substring(0, 10);
                // }
            });
        })
        this.$bus.$on("getTableListAttch", data => {
            this.fileList = data
        })
    }
};
</script>

<style lang="scss" scoped>
/deep/ .el-table th.must > .cell:before {
    content: "* ";
    color: #ff1818;
}

/deep/
.ccui-multifunctional-table-wrapper
.el-table
.el-table__footer-wrapper
tbody
td {
    font-size: 13px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 600;
    //   color: #0089ef;
}

/deep/ .ccui-multifunctional-table-wrapper .el-table__header-wrapper th {
    border-right: 1px solid #edf2fc;
}

/deep/ .ccui-multifunctional-table-wrapper .el-table td {
    border-right: 1px solid #edf2fc;
}

.commonClass {
    margin-top: 5px;
}

/deep/ .el-table__row .el-tooltip {
    margin: 0 auto;
}

/deep/ .el-table--border {
    th:last-of-type.gutter {
        display: table-cell !important;
        width: 0px !important;
    }
}

/deep/ .el-table__row td .el-tooltip {
    width: 100% !important;
}
</style>
